<?php

/*
* Class teia\webdev\php\core\SessionWrapper
* Core class wrapping PHP support for session management
*
* @author Bernardo Quibiana
* @date created: 20111011
*
* @date modified: 20111018
* @modified: Bernardo Quibiana
*/

// namespace declaration: Abstract Data Types
namespace teia\webdev\php\core;

require_once 'User.inc';
require_once 'ShoppingCart.inc';

class SessionWrapper {
	
	protected static $started = false;	// whether the php session started
	protected static $startup = true;	// whether it is the first pass
	
	/**
	 * Start a session and load global variables (eg: user, cart...)
	 * @return boolean returns true if a session was successfully started, otherwise false.
	 */
	static function start() {
		self::$startup = false;
		
		if (!self::$started) {
			if (self::$started = session_start()) {
				$usr = self::get_user();
				$cart = self::get_cart($usr);
			}	
		}
		return self::$started;
	}
	
	/*
	 * User handling functions
	 */
	
	/**
	 * Get the user object of the current session, or instantiate a guest user if no user is defined
	 * @return teia\webdev\php\core\User the user object
	 */
	static function get_user() {
		if (self::$startup) {
			self::start();
		}
		
		if (isset($_SESSION['_user'])) {
			$user = $_SESSION['_user'];
		} else {
			$user = new User();
			$_SESSION['_user'] = $user;
		}
		
		return $user;
	}
	
	static function logout_user() {
		if (isset($_SESSION['_user'])) {
			if ($user->is_logged()) {
				// save user�s data, such as cart
				$user = $_SESSION['_user'];
					
				// remove user from session
				unset($_SESSION['_user']);
				return true;
			}
		}
		return false;
	}
	
	/*
	 * Shopping cart handling functions
	 */
	
	/**
	 * Get the cart object of the current session, or instantiate a saved cart for the speficied user
	 * @param teia\webdev\php\core\User $usr_obj the user object of the current session
	 * @return teia\webdev\php\core\ShoppingCart the user object
	 */
	static function get_cart($usr_obj) {
		if (self::$startup) {
			self::start();
		}
		
		if (isset($_SESSION['_cart'])) {
			$cart = $_SESSION['_cart'];
		} else {
			$cart = new ShoppingCart();
			$_SESSION['_cart'] = $cart;
		}
		return $cart;
	}
	
	static function get_prod_it_track() {
		if (self::$startup) {
			self::start();
		}
		
		if (isset($_SESSION['_prod_it_track'])) {
			$track = $_SESSION['_prod_it_track'];
		} else {
			$track = new ProductItemTrack();
			$_SESSION['_prod_it_track'] = $track;
		}
		return $track;
	}
	static function get_usr_browser() {
		return null;
	}
	
	static function get_usr_os() {
		return null;
	}
	
	static function close() {
		session_destroy();
		self::$started = false;
	}
}

?>
